const app = getApp() // 引入app
import _request from '../../utils/request.js'
import {
  getSevenDay,
  getToDay,
  regMobile
} from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    marginBottom: app.globalData.marginBottom,
    imgUrl: app.globalData.imgUrl, //全局img路径
    activeNames: [],
    showLength: 2,
    imglist: [{
        id: 1,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 2,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 3,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 4,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 5,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
    ],
    active: 0,
    evaluatelist: [1, 1, 1, 1, 0.5],
    showtext: true,
    showbrief: true,
    showadept: true,
    hairlist: null,
    bool: '',
    cardServerList: [],
    exhiblist: [],
    lastId: '',
    hair: '',
    showTerminateDialog: true,
    mobileinfovisible: false,
    stylistId: '',
    userid: '',
    nexus: '',
    storeId: '',
    comprehensive:0,
    commentList:[],
    page:1,
    shopimgUrl: app.globalData.shopimgUrl,
    status:''
  },

  // 获取点击时间
  onClickTime(e) {
    const {
      orderWeek,
      Key
    } = e.detail
    const {
      serverStoreObj
    } = this.data
    this.setData({
      serverStoreList: [],
    })
    let list = serverStoreObj[Key].map(item => {
      let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
      let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
      return {
        ...item,
        'newdistance': newdistance
      }
    })
    this.setData({
      serverStoreList: list,
      today: orderWeek
    })
  },

  // 展示更多
  showmore() {
    this.setData({
      showLength: this.data.cardServerList.length
    })
  },

  // 查看详情作品
  onDetail(e) {
    const {
      item
    } = e.currentTarget.dataset
    // let obj = JSON.stringify(item)
    wx.navigateTo({
      url: '/pages/workdetails/index?id=' + item.opusId,
    })
  },

  //点击图片进行预览，长按保存分享图片
  previewImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.item, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.item] // 需要预览的图片http链接列表
    })
  },

  // 展示3条
  showmuch() {
    this.setData({
      showLength: 2
    })
  },

  // 点击展示更多服务
  onShowList(e) {
    const {
      id,
      bool
    } = e.currentTarget.dataset
    this.setData({
      cardServerList: this.data.cardServerList.map(item => {
        if (item.serviceId == id && bool != true && id) {
          return {
            ...item,
            bool: true
          }
        } else if (bool == true) {
          return {
            ...item,
            bool: false
          }
        } else {
          return {
            ...item,
            bool: false
          }
        }
      })
    })
  },

  // 点击解约
  terminate(){
    var that = this;
    wx.showModal({
      title: '是否与该美发师解约？',
      success(res) {
        if (res.confirm) {
          _request.postObj('/store/breakStoreNexus', {
            stylistId: that.data.hair.stylistId,
            storeId: that.data.storeId,
            nexus: that.data.nexus
            }).then((res) => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '解约成功',
                  icon: 'none',
                  duration: 2000
                })
                setTimeout(() => {
                  wx.navigateBack({
                    delta: -1,
                  })
                }, 1000);
                
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
        
            })
        } else if (res.cancel) {}
      }
    })
  },
  // 邀请入驻
  apply(){
    wx.navigateTo({
      url: '/pages/hairstylistdetails/joinshop/index?stylistId=' + this.data.hair.stylistId,
    });
    var that = this;
  },

  // 同意
  agree(){
    var that = this;
    wx.showModal({
      title: '是否要同意该美发师的申请？',
      success(res) {
        if (res.confirm) {
          _request.postObj('/store/nexus', {
            stylistId: that.data.hair.stylistId,
            storeId: that.data.storeId,
            nexus: that.data.nexus
            }).then((res) => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '入驻成功！',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
        
            })
        } else if (res.cancel) {}
      }
    })
  },

  // 拒绝
  refuse(){
    var that = this;
    wx.showModal({
      title: '是否要拒绝该美发师的申请？',
      success(res) {
        if (res.confirm) {
          _request.postObj('/store/refuse', {
            stylistUserId: that.data.hair.stylistId,
            storeUserId: that.data.storeId,
            type: that.data.nexus
            }).then((res) => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '拒绝成功！',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
        
            })
        } else if (res.cancel) {}
      }
    })
  },
  showmobileinfo: function() {
    this.setData({
      mobileinfovisible: true
    })
  },
  handleClosemobileinfo: function() {
    this.setData({
      mobileinfovisible: false
    })
  },

  // 显示电话
  onMobile(e) {
    const {
      mobile
    } = e.currentTarget.dataset
    this.setData({
      showoverlay: true
    })
  },

  // 拨打电话
  goMobile() {
    wx.makePhoneCall({
      phoneNumber: this.data.hairlist.mobile //仅为示例，并非真实的电话号码
    })
  },

  // 隐藏电话
  onClickHide() {
    this.setData({
      showoverlay: false
    })
  },
  // 关闭弹窗
  onClose() {
    this.setData({ show: false });
  },

  // 点击展示美发师优惠
  onShowmeal() {
    this.setData({
      showmeal: true
    })
  },
  // 隐藏美发师优惠
  onClickmealHide() {
    this.setData({
      showmeal: false
    })
  },
  // 领取优惠券
  getdrawCoupon(e) {
    const {
      couponId,
      type
    } = e.currentTarget.dataset.item
    _request.postObj('/storeCouponCode/drawCoupon', {
      userId: wx.getStorageSync('userid'),
      type: type,
      couponId: couponId,
    }).then((res) => {
      if (res.data.code == 200) {
        // 美发师详情
        this.getCard()
        this.setData({
          showmeal: false
        })
      }
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 购买套餐
  toBuymeal(e) {
    const {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/buymealdetails/index?id=' + id,
    })
  },

  // 解约
  onTerminate(){
  _request.postObj('/store/breakStoreNexus', {
    stylistId: this.data.hair.stylistId,
    storeId: this.data.storeId,
    nexus: this.data.nexus
    }).then((res) => {
      this.setData({ show: false });
      if (res.data.code === 200) {
        wx.showToast({
          title: '解约成功',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '解约失败',
          icon: 'none',
          duration: 2000
        })
      }

    })
  },

  // 发型师评论详情
  getStylistCommentList(e, id, show) {
    if (show) {
      wx.showNavigationBarLoading() // 顶部加载状态
    }
    _request.get('/stylistComment/getStylistCommentList', {
      page: e,
      size: 10,
      stylistId: id,
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      var commentList = res.data.data;
      for (let i = 0; i < commentList.length; i++) {
        commentList[i]['createtime'] = (commentList[i]['createtime']).substring(0, 10);
        commentList[i]['bool'] = commentList[i]['comment'].length >= 60 ? true : false;
        commentList[i]['stylistReply'] = decodeURIComponent(commentList[i]['stylistReply']);
        commentList[i]['reply'] = decodeURIComponent(commentList[i]['reply']);
      }
      // var listTemps = this.data.commentList;
      // for (let i = 0; i < commentList.length; i++) {
      //   listTemps.push(commentList[i]);
      // }
      this.setData({
        commentList: [...this.data.commentList, ...commentList],
      });
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    }).catch((error) => {
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
      // console.log(error, 'error');
    })
  },


  // 前往门店详情
  toShopdetails(e) {
    const {
      item
    } = e.currentTarget.dataset
    let obj = JSON.stringify(item)
    wx.navigateTo({
      url: '/pages/shopdetails/index?shop=' + obj,
    })
  },

  // 获取服务门店数据
  getStylistStores(e, id, show) {
    if (show) {
      wx.showNavigationBarLoading() // 顶部加载状态
    }
    _request.postObj('/stylistServer/getStylistStores', {
      page: e,
      size: 10,
      stylistId: id,
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      if (res.data.data && res.data.data != null) {
        this.setData({
          serverStoreList: res.data.data.map(item => {
            let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
            let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
            return {
              ...item,
              newdistance
            }
          })
        })
      }
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    }).catch((error) => {
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
      console.log(error, 'error');
    })
  },

  // 获取七日门店数据
  getStylistStoresInfos(id, show) {
    if (show) {
      wx.showNavigationBarLoading() // 顶部加载状态
    }
    _request.postObj('/stylistServer/getStylistStoresInfos', {
      stylistId: id,
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      let data = res.data.data ? res.data.data : []
      let today = getSevenDay()[0].Key
      let list = data[today] ? data[today] : []
      if (res.data.data && res.data.data != null) {
        this.setData({
          today,
          serverStoreObj: res.data.data,
          serverStoreList: list.map(item => {
            let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
            let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
            return {
              ...item,
              newdistance
            }
          })
        })
      }
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    }).catch((error) => {
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
      console.log(error, 'error');
    })
  },

  // 预约
  onHairMake(e) {
    const {
      item
    } = e.currentTarget.dataset
    let hair = JSON.stringify(this.data.hair)
    let shop = JSON.stringify(item)
    wx.navigateTo({
      url: '/pages/bookingorder/index?hair=' + hair + '&shop=' + shop,
    })
  },

  // 美发师获取作品
  getScreenDynamicState() {
    let data = {
      featureId: 0,
      hairstyleId: 0,
      lastId: 0,
      stylistId: this.data.hair.stylistId,
      userId: wx.getStorageSync('userid'),
    }
    _request.postObj('/dynamicState/getScreenDynamicState', {
      ...data
    }).then((res) => {
      this.setData({
        exhiblist: res.data.data,
        lastId: res.data.data[res.data.data.length - 1].opusId
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 点击作品收藏
  onLove(e) {
    const {
      opusid,
      iscollection
    } = e.currentTarget.dataset
    _request.postObj('/storeStylist/oupsCollection', {
      stylistId: this.data.hair.stylistId,
      opusId: opusid,
      userId: wx.getStorageSync('userid'),
      type: iscollection ? 0 : 1
    }).then((res) => {
      if(res.data.code == 200){
        this.setData({
          exhiblist: this.data.exhiblist.map((item => {
            if (item.opusId === opusid) {
              return {
                ...item,
                "isCollection": !iscollection,
                "collection": !iscollection ? (item.collection + 1) : (item.collection - 1)
              }
            }
            return item
          }))
        })
        wx.showToast({
          title: iscollection ? '取消收藏' : '收藏成功',
          icon: 'none',
          duration: 2000
        })
      } else{
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        })
      }
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 点击收藏
  onCollection(e) {
    const {
      stylistid
    } = e.currentTarget.dataset
    _request.postObj('/store/storeCollection', {
      userId: wx.getStorageSync('userid'),
      stylistId: stylistid,
      type: this.data.bool ? '0' : '1'
    }).then((res) => {
      this.setData({
        bool: !this.data.bool
      })
      wx.showToast({
        title: this.data.bool ? '收藏成功' : '取消收藏',
        icon: 'none',
        duration: 2000
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
    console.log(e);
  },

   // tabs切换
   onChange(event) {
    this.setData({
      active: event.detail.index
    })
  },


  // 查看全文
  toMore(e) {
    let index = e.currentTarget.dataset.index;
    var commentList = this.data.commentList;
    commentList[index]['showtext'] = commentList[index]['showtext'] ? false : true;
    this.setData({
      commentList: commentList
    })
  },

  // 查看更多详情简介
  toMorebrief() {
    this.setData({
      showbrief: !this.data.showbrief
    })
  },

  // 查看更多详情擅长
  toMoreadept() {
    this.setData({
      showadept: !this.data.showadept
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let storeId = wx.getStorageSync('storeId');
    let hair = JSON.parse(decodeURIComponent(options.hair))
    this.setData({
      hair: hair,
      active: hair.active,
      status:options.status != null ? options.status : -1
    })
    console.log(options,'hair');

    
    this.setData({
      stylistId: this.data.hair.stylistId,
      userid: this.data.hair.userId,
      nexus: this.data.hair.nexus,
      storeId: storeId
    })

    // 发型师详情
    _request.postObj('/storeStylist/card', {
      stylistId: this.data.hair.stylistId,
      userid:  this.data.hair.userId,
      nexus: this.data.nexus,
      storeId: storeId
    }).then((res) => {
      let data = res.data.data
      data.newmobile = regMobile(data.mobile);
      data.cardPackages.map(item => {
        if (item.type == 1) {
          this.setData({
            onebool: true
          })
        } else if (item.type == 2) {
          this.setData({
            morebool: true
          })
        }
      })
      var cardServerList = data.cardServerItems || []
      if(cardServerList && cardServerList.length > 0){
        cardServerList = cardServerList.map(item => {
          return {
            ...item,
            bool: false
          }
        });
      }
      if(data.adept && data.adept != null){
        data.newadept = data.adept.split(","); //字符分割 
      }
      this.setData({
        cardServerList: cardServerList,
        hairlist: data,
        bool: data.isCollection
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    //获取美发师评分
    _request.get('/stylistComment/getEvaluate', {
      stylistId: this.data.hair.stylistId
    }).then((res) => {
      this.setData({
        comprehensive:res.data.data.comprehensive   
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 查询美发师服务
    _request.get('/specialActivity/cardStylistServers', {
      stylistId: this.data.stylistId,
      userId: wx.getStorageSync('userid'),
      page: 1,
      size: 10,
    }).then((res) => {
      this.setData({
        cardServerList: res.data.data.cardServerItems.map(item => {
          return {
            ...item,
            bool: false
          }
        })
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 获取洗吹
    // 获取洗剪吹
    // 发型师评论详情
    this.getStylistCommentList(1, this.data.hair.stylistId, false)
    // 获取服务门店数据
    // this.getStylistStores(1, this.data.hair.stylistId, false)
    // 获取七日门店数据
    this.getStylistStoresInfos(this.data.hair.stylistId, false)
    
  },
  onShow(){
    // 美发师获取作品
    this.getScreenDynamicState()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const {
      active,
      page,
      hair,
      lastId,
      exhiblist
    } = this.data
    if (active == 2) { // 获取更多评价
      this.setData({
        page: page + 1
      })
      this.getStylistCommentList(this.data.page, hair.stylistId, true)
    } else if (active == 1) { // 获取更多作品
      this.getScreenDynamicState(lastId)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  }
})